var bg;//背景页

$(function() {


	//背景页的相关数据
	bg = chrome.extension.getBackgroundPage();

	//初始化设置
	$('#dtime').val(bg.config['conf']['dtime']);
	$('#fid').val(bg.config['conf']['fid']);
	$('#keys').val(bg.config['conf']['keys'].join(' '));

	//打开论坛页面
	$('#open_page').click(function()
	{
		chrome.tabs.create({url: 'http://bbs.ngacn.cc/thread.php?fid=570'});
	})
	// 测试扫描和桌面通知
	$('#show_notification').click(()=>
	{
		bg.scan_thread('570',['你']);
	});

	//开始扫描
	$('#star_scan').click(()=>
	{
		bg.config['conf']['dtime']=$('#dtime').val();
		bg.config['conf']['fid']=$('#fid').val();
		bg.config['conf']['keys']=$('#keys').val().split(' ')
		bg.star_scan();
		$('#star_scan').hide();
		$('#stop_scan').show();
	})

	//停止扫描
	$('#stop_scan').click(()=>
	{
		bg.stop_scan();
		$('#stop_scan').hide();
		$('#star_scan').show();
	})

	//根据config.conf.running状态初始化开始停止按钮
	if(bg.config.conf.running)
	{

		$('#star_scan').hide();
		$('#stop_scan').show();
	}
	else
	{
		$('#stop_scan').hide();
		$('#star_scan').show();
	}

	//根据bg.config['data']中的数据填充最近10条记录
	$.each(bg.config['data'],function(k,v){
		//console.log(k);
		//console.log(v);
		var d=new Date(v['postdate']*1000);
		$('#last10topic').append(
			$('<div id="'+(k+1)+'" class="">').append(
				'<span class="">'+k+'</span>',
				'<a class="subject" href="http://bbs.ngacn.cc'+v['tpcurl']+'">'+v['subject'].slice(0,25)+'</a>',
				'<span class="time">'+d.format('yyyy-MM-dd h:m:s')+'</span>'
			)
		)
	});
	
	//为最近10条记录的链接添加click事件
	$('.subject').click(function()
	{
		chrome.tabs.create({url: $(this).get(0).href});
		return false;
	
	})
});

// 获取当前选项卡ID
function getCurrentTabId(callback)
{
	chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
	{
		if(callback) callback(tabs.length ? tabs[0].id: null);
	});
}

//格式化时间戳
//console.log(newDate.format('yyyy-MM-dd h:m:s'));
Date.prototype.format = function(format) {
    var date = {
       "M+": this.getMonth() + 1,
       "d+": this.getDate(),
       "h+": this.getHours(),
       "m+": this.getMinutes(),
       "s+": this.getSeconds(),
       "q+": Math.floor((this.getMonth() + 3) / 3),
       "S+": this.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
       format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
       if (new RegExp("(" + k + ")").test(format)) {
           format = format.replace(RegExp.$1, RegExp.$1.length == 1
              ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
       }
    }
    return format;
}